iT邦幫忙

2021 iThome 鐵人賽

DAY 6
0
Software Development

全端開發包括測試自己一條龍!系列 第 6

Day 6 - Laravel 8.0 如何快速建立API

  • 分享至 

  • xImage
  •  

Day 3 - 如何運用 Laravel 框架設計模式規劃大型專案,當中提到Controller-Service-Repository的溝通,今天會介紹到底如何撰寫.

  1. 首先建立model及migration

app/Models/Post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = [
        'user_id',
        'title',
        'content'
    ];

    /**
     * 將資料作轉換
     *
     * @var array
     */
    protected $casts = [
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s'
    ];
}

database/migrations/2021_09_19_082930_create_posts_table

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id')->comment('發文者');
            $table->string('title')->unique()->comment('標題');
            $table->string('content')->comment('內文');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}
  1. 首先建立Controller, Service, Repository
$ sail artisan make:controller PostController
$ sail artisan make:service PostService
$ sail artisan make:repository PostRepository
  1. 設定routes/api.php,讓我們能透過路由對應到指定的Controller
    • 可以看到我們把發布文章的API設定在jwt.auth的Group當中,這麼一來我們就能確保沒經過身份驗證的使用者無法建立文章.
<?php
use App\Http\Controllers\PostController;
use Illuminate\Support\Facades\Route;


Route::middleware(['jwt.auth'])->group(function () {
    Route::group(['prefix' => 'post'], function () {
        Route::post('/', [PostController::class, 'create']);
    });
});

  1. 調整PostController,可以看到我們在construct地方自動注入了PostService,藉此可以調用內部的function
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Services\PostService;
use Illuminate\Http\JsonResponse;

class PostController extends Controller
{
    protected $service;

    public function __construct(PostService $service)
    {
        $this->service = $service;
    }

    /**
     * 建立文章
     * @param Request $request
     * @return JsonResponse
     */
    public function create(Request $request): JsonResponse
    {
        $result = $this->service->create($request->all());
        return response()->json($result);
    }
}
  1. 調整PostService,同上在Service自動注入Repository
<?php

namespace App\Services;

use Yish\Generators\Foundation\Service\Service;
use App\Repositories\PostRepository;
use Illuminate\Support\Arr;

class PostService
{
    /**
     * @var PostRepository
     */
    protected $post_repository;

    public function __construct(PostRepository $post_repository)
    {
        $this->post_repository = $post_repository;
    }

    /**
     * 建立文章
     * @param array $data
     * @return mixed
     */
    public function create(array $data)
    {
        $title = Arr::get($data, 'title');
        $content = Arr::get($data, 'content');
        $post = $this->post_repository->createPost($title, $content);

        return $post;
    }
}
  1. 接下來建立Repository
<?php

namespace App\Repositories;

use App\Models\Post;
use App\Models\User;
use Exception;
use Illuminate\Support\Facades\Auth;

class PostRepository
{
    /**
     * 建立文章
     *
     * @param string $title 標題
     * @param string $content 內文
     * @return mixed
     */
    public function createPost(string $title, string $content)
    {

        try {
            $user = Auth::guard('api')->user();

            $post = new Post();
            $post->title = $title;
            $post->content = $content;
            $post->user_id = $user->id;
            $post->save();

            return $post;
        } catch (Exception $e) {
            dd($e);
        }
    }
}

上述都建立完後,我們就可以透過Postman Call API來建立新的文章

如此一來就簡單快速的完成了發布文章的API,接下來文章會介紹寫Request validation與Error handler來優化我們的API.


上一篇
Day 5 - 使用JWT Token幫Laravel 8.0做Authentication
下一篇
Day 7 - 淺談Laravel資料庫關聯的運用
系列文
全端開發包括測試自己一條龍!10
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
aa4731073
iT邦新手 4 級 ‧ 2022-07-19 10:52:56

請問一下,如果只想要顯示“時間、日期”的話,是只要修改app/Models/Post.php就好了嗎?

我要留言

立即登入留言